<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="品牌名称" prop="name">
        <el-input v-model.trim="dataForm.name" placeholder="商品名称" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="品牌英文名" prop="englishName">
        <el-input v-model.trim="dataForm.englishName" placeholder="品牌英文名" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="品牌缩写" prop="nameAbbreviation">
        <el-input v-model="dataForm.nameAbbreviation" placeholder="品牌缩写" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="品牌产地" prop="placeOrigin">
        <el-input v-model="dataForm.placeOrigin" placeholder="品牌产地" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="品牌编号" prop="code">
        <el-input v-model.trim="dataForm.code" placeholder="品牌编号" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="官方网址" prop="officialWebsite">
        <el-input v-model="dataForm.officialWebsite" placeholder="官方网址" style="width:500px"></el-input>
      </el-form-item>
      <el-form-item label="品牌排序" prop="sort">
        <el-input type="number" v-model="dataForm.sort" placeholder="品牌排序" style="width:100px"></el-input>
      </el-form-item>

      <el-row :gutter="15">
        <el-col :span="5">
          <el-form-item label="一级分类" prop="">
            <el-select v-model="selectParentClass" filterable placeholder="请选择" value="selectParentClass" @change="selectSubClass=''">
              <el-option :value="-1" :key="-1" label="请选择"></el-option>
              <el-option
                v-for="(item,index) in goodsClassList"
                :key="index"
                :label="item.className"
                :value="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="二级分类" prop="" v-if="selectParentClass !== -1">
            <el-select v-model="selectSubClass" filterable placeholder="请选择" value="selectSubClass">
              <el-option
                v-for="(item,index) in (goodsClassList[selectParentClass].subGoodsClassList)"
                :key="item.id"
                :label="item.className"
                :value="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button @click="addRow()" plain type="primary">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-if="this.dataForm.classList.length != 0"
                         :data="this.dataForm.classList"
                         border
                         style="width: 100%">
        <el-table-column v-show="flag == true"
          prop="selectSubClassId"
          header-align="center"
          align="center"
          label="二级分类ID">
        </el-table-column>
        <el-table-column
          prop="selectSubClassName"
          header-align="center"
          align="center"
          label="二级分类名称">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-popconfirm
              title="确定删除吗？">
              <el-button slot="reference" @click="deleteRow(scope.$index)"> 删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-form-item label="是否启用" prop="enableState">
        <template>
          <el-radio v-model="dataForm.enableState" :label="0">否</el-radio>
          <el-radio v-model="dataForm.enableState" :label="1">是</el-radio>
        </template>
      </el-form-item>
      <el-form-item label="品牌logo图" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="this.$http.adornUrl(`/brand/uploadBrand?token=${this.$cookie.get('token')}`)"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.logoUrl" :src="dataForm.logoUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌大图" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          :action="this.$http.adornUrl(`/brand/uploadBrand?token=${this.$cookie.get('token')}`)"
          :show-file-list="false"
          :on-success="handleAvatarSuccess1"
          :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.imageUrl" :src="dataForm.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="品牌故事" prop="story">
        <el-input type="textarea" v-model="dataForm.story" placeholder="品牌故事"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="remarks">
        <el-input v-model="dataForm.remarks"  type="textarea" placeholder="描述"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        flag: false,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        addOrUpdateVisible: false,
        selectParentClass: -1,
        selectSubClass: '',
        goodsClassList: [],
        dataForm: {
          id: 0,
          code: '',
          name: '',
          englishName: '',
          placeOrigin: '',
          nameAbbreviation: '',
          officialWebsite: '',
          sort: '',
          enableState: '',
          createTime: '',
          story: '',
          remarks: '',
          logoUrl: '',
          classList: [],
          imageUrl: ''
        },
        dataRule: {
          name: [
            { required: true, message: '品牌名称不能为空', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '品牌编号不能为空', trigger: 'blur' }
          ],
          nameAbbreviation: [
            { required: true, message: '品牌缩写不能为空', trigger: 'blur' }
          ],
          sort: [
            { required: true, message: '请输入品牌排序', trigger: 'blur' },
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '排序应为正整数', trigger: 'blur' }
          ],
          enableState: [
            { required: true, message: '请输入启用状态', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        debugger
        // 请求分类
        // Object.assign(this.$data, this.$options.data())
        this.dataForm.logoUrl = ''
        this.dataForm.imageUrl = ''
        this.dataForm.classList = []
        this.selectParentClass = -1
        this.selectSubClass = ''
        this.visible = true
        this.dataForm.id = id || 0
        debugger
        this.$nextTick(() => {
          debugger
          if (this.$refs['dataForm'] !== undefined) {
            this.$refs['dataForm'].resetFields()
          }
          this.$http({
            url: this.$http.adornUrl(`/activity/goods/queryClassList`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.goodsClassList = data.data
            }
            console.log(this.goodsClassList)
            console.log(this.dataForm.classList)
          })
          if (this.dataForm.id) {
            debugger
            this.$http({
              url: this.$http.adornUrl(`/brand/getBrandById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                debugger
                this.dataForm.name = data.data.name
                this.dataForm.code = data.data.code
                this.dataForm.nameAbbreviation = data.data.nameAbbreviation
                this.dataForm.officialWebsite = data.data.officialWebsite
                this.dataForm.sort = data.data.sort
                this.dataForm.enableState = data.data.enableState
                this.dataForm.logoUrl = data.data.logoUrl != null ? 'https://image.yilianbaihui.cn/consumer/' + data.data.logoUrl : ''
                this.dataForm.imageUrl = data.data.imageUrl != null ? 'https://image.yilianbaihui.cn/consumer/' + data.data.imageUrl : ''
                this.dataForm.story = data.data.story
                this.dataForm.remarks = data.data.remarks
                this.dataForm.englishName = data.data.englishName
                this.dataForm.placeOrigin = data.data.placeOrigin
                for (var i = 0; i < data.data.list.length; i++) {
                  this.dataForm.classList.push({selectSubClassId: data.data.list[i].id, selectSubClassName: data.data.list[i].className})
                }
              }
            })
          }
        })
      },
      addRow () {
        debugger
        let PraIndex = this.selectParentClass
        let SubIndex = this.selectSubClass
        if (SubIndex === '') {
          this.$message.error('请选择分类！')
          return
        }
        for (var i = 0; i < this.dataForm.classList.length; i++) {
          if (this.goodsClassList[PraIndex].subGoodsClassList[SubIndex].id === parseInt(this.dataForm.classList[i].selectSubClassId)) {
            this.$message.error('以有该分类！')
            return
          }
        }
        this.dataForm.classList.push({
          selectSubClassId: this.goodsClassList[PraIndex].subGoodsClassList[SubIndex].id,
          selectSubClassName: this.goodsClassList[PraIndex].subGoodsClassList[SubIndex].className
        })
      },
      deleteRow (index) {
        this.dataForm.classList.splice(index, 1)
      },
      handleAvatarSuccess (res, file) {
        this.dataForm.logoUrl = res.data
      },
      beforeAvatarUpload (file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg' || 'image/png'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        return isJPG
      },
      handleAvatarSuccess1 (res, file) {
        this.dataForm.imageUrl = res.data
      },
      // 表单提交
      dataFormSubmit () {
        debugger
        if (this.dataForm.logoUrl !== '') {
          let index = this.dataForm.logoUrl.lastIndexOf('\/')
          this.dataForm.logoUrl  = 'brand/' + this.dataForm.logoUrl.substring(index + 1, this.dataForm.logoUrl.length)
        }
        if (this.dataForm.imageUrl !== '') {
          let index = this.dataForm.imageUrl.lastIndexOf('\/')
          this.dataForm.imageUrl  = 'brand/' + this.dataForm.imageUrl.substring(index + 1, this.dataForm.imageUrl.length)
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            console.log(this.dataForm.classList.length)
            if (this.selectSubClass === -1) {
              this.$message.error('请选择二级分类')
              return
            }
            if (this.dataForm.logoUrl.length === 0 || this.dataForm.imageUrl.length === 0) {
              this.$message.error('LOGO图和大图不能为空')
              return
            }
            this.$http({
              url: this.$http.adornUrl(`/brand/${!this.dataForm.id ? 'addBrandGoods' : 'modifyBrandById'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'name': this.dataForm.name,
                'code': this.dataForm.code,
                'nameAbbreviation': this.dataForm.nameAbbreviation,
                'sort': this.dataForm.sort,
                'logoUrl': this.dataForm.logoUrl,
                'imageUrl': this.dataForm.imageUrl,
                'officialWebsite': this.dataForm.officialWebsite,
                'story': this.dataForm.story,
                'remarks': this.dataForm.remarks,
                'classList': this.dataForm.classList,
                'enableState': this.dataForm.enableState,
                'englishName': this.dataForm.englishName,
                'placeOrigin': this.dataForm.placeOrigin
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
